package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.service.CommandCenterStaffRelService;
import com.api.shopapi.service.InstitutionStaffRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("InstitutionStaffRel")
public class InstitutionStaffRelController extends BaseController{

    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    //编辑
    @RequestMapping(value = "Edit",method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String institutionCode = jsonObject.getString("institutionCode");
            JSONArray listStaff = jsonObject.getJSONArray("listStaff");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/CommendCenterStaffRel/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            //删除老的关系
            List<InstitutionStaffRel> listStaffRel = institutionStaffRelService.getListByInstitutionCode(institutionCode);
            for(InstitutionStaffRel institutionStaffRel : listStaffRel){
                institutionStaffRelService.deleteByInstitutionStaffRelCode(institutionStaffRel.getInstitutionStaffRelCode());
            }

            //增加新的关系
            for (int k = 0; k < listStaff.size(); k++) {

                JSONObject staffTemp = listStaff.getJSONObject(k);

                InstitutionStaffRel commandCenterStaffRel = new InstitutionStaffRel();
                commandCenterStaffRel.setInstitutionStaffRelCode(UUID.randomUUID().toString());
                commandCenterStaffRel.setInstitutionCode(institutionCode);
                commandCenterStaffRel.setStaffCode(staffTemp.getString("staffCode"));
                institutionStaffRelService.insert(commandCenterStaffRel);
            }


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        }catch (Exception e){
            insertError("/CommendCenterStaffRel/Edit",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


}
